package com.example.springblog.utils;

import lombok.extern.slf4j.Slf4j;
import org.springframework.util.DigestUtils;

import java.io.UnsupportedEncodingException;
import java.util.UUID;
@Slf4j
public class SecurityUtils {
   //对密码进行加密
    public static String encrypt(String password) throws UnsupportedEncodingException {
        //随机生成盐值
        String salt = UUID.randomUUID().toString().replace("-" , "");
        //生成密文
        String secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));

        return salt + secretString;
    }

    public static Boolean verify(String password , String finalpassword){
        if(finalpassword == null || finalpassword.length() != 64){
            log.info("长度不够");
            return false;
        }
        String salt = finalpassword.substring(0,32);
        String secretString = null;
        try {
            secretString = DigestUtils.md5DigestAsHex((salt+password).getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException(e);
        }
        return (salt+secretString).equals(finalpassword);
    }
}
